<template>
  <div>
    <div style="display: flex;justify-content: space-between;margin: 5px 0">
      <el-input placeholder="请输入用户名" v-model.trim="search" style="margin-bottom: 5px;width: 300px">
        <el-button type="primary" slot="append" icon="el-icon-search" @click="handleQuery"></el-button>
      </el-input>
      <span>
        <el-button size="small" type="primary" style="margin-right: 70px"
                   @click="dialog=true;dialogType=0">添加用户</el-button>
      </span>
    </div>

    <el-table
      :data="tableData"
      border
      style="width: 100%">
      <el-table-column fixed prop="username" label="用户名" min-width="100" align="center"></el-table-column>
      <el-table-column prop="phone" label="电话" min-width="100" align="center"></el-table-column>
      <el-table-column prop="email" label="邮箱" min-width="100" align="center"></el-table-column>
      <el-table-column prop="roleNames" label="角色" min-width="100" align="center"></el-table-column>
      <el-table-column align="center" fixed="right" label="状态" min-width="40">
        <template slot-scope="scope">
          <el-button v-if="scope.row.status===1" @click="handleDisable(scope.row)" type="success" size="mini">正常
          </el-button>
          <el-button v-if="scope.row.status===0" @click="handleEnable(scope.row)" type="danger" size="mini">已禁用
          </el-button>
        </template>
      </el-table-column>
      <el-table-column align="center" fixed="right" label="操作" min-width="100">
        <template slot-scope="scope">
          <el-button-group>
            <el-button @click="handleEdit(scope.row)" type="primary" size="mini">编辑</el-button>
            <el-button @click="handleReset(scope.row)" type="warning" size="mini">重置密码</el-button>
            <el-button @click="handleDelete(scope.row)" type="danger" size="mini">删除</el-button>
          </el-button-group>
        </template>
      </el-table-column>
    </el-table>

    <el-row>
      <el-col :offset="14" :span="9">
        <el-pagination
          @current-change="currentChange"
          :page-size="pageSize"
          layout="prev, pager, next"
          :total="total">
        </el-pagination>
      </el-col>
    </el-row>

    <el-dialog :title="dialogType===0?'添加用户':'编辑用户'" :visible.sync="dialog" width="600px" @close="closeDialog">
      <el-form :model="userForm" ref="userForm">

        <el-form-item label="用户名" label-width="80px" prop="username"
                      :rules="[{required:true,message:'请输入用户名',trigger:'blur'}]">
          <el-input v-model.trim="userForm.username" autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item label="角色" label-width="80px">
          <el-select v-model="userForm.roleList" multiple placeholder="请选择" style="width: 100%">
            <el-option v-for="item in roles" :key="item.id" :label="item.roleName" :value="item.id"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="电话" label-width="80px">
          <el-input v-model="userForm.phone" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" label-width="80px">
          <el-input v-model="userForm.email" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer" style="margin-right: 50px">
        <el-button @click="closeDialog">取 消</el-button>
        <el-button type="primary" @click="submitUserForm">确 定</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>

export default {
  name: "UserManager",
  data() {
    return {
      dialog: false,
      userForm: {
        id: '',
        username: '',
        roleList: [],
        phone: '',
        email: ''
      },
      dialogType: '', //0、新增  1、修改

      roles: [],

      tableData: [],
      search: '',
      pageSize: 9,  //每页显示条数
      total: 0,    //总条数
      currentPage: 1,  //当前页
    }
  },
  methods: {
    submitUserForm() {
      this.$refs['userForm'].validate(valid => {
        if (valid) {
          let url = this.dialogType === 0 ? '/user/addUser' : '/user/editUser';
          this.$axios.post(url, this.$qs.stringify(this.userForm)).then(res => {
            if (res.code === 200) {
              this.$message({type: 'success', message: '提交成功！'});
              this.closeDialog();
              this.getData();
            }
          })
        }
      });
    },
    handleQuery() {
      this.currentPage = 1;
      this.getData();
    },
    handleEdit(data) {
      let roleList = [];
      for (let index in data.roleList) {
        roleList.push(data.roleList[index].id)
      }
      this.dialogType = 1;
      this.dialog = true;
      this.userForm = {id: data.id, username: data.username, roleList: roleList, phone: data.phone, email: data.email};
    },
    handleReset(data) {
      this.$confirm('确认重置密码?', '重置密码', {type: 'warning'}).then(() => {
        this.$axios.post('/user/resetPassword', this.$qs.stringify({id: data.id})).then(res => {
          if (res.code === 200) {
            this.getData();
            this.$message({type: 'success', message: '重置密码成功!'});
          }
        })
      }).catch(() => {
      });
    },
    handleDelete(data) {
      this.$confirm('确认删除?', '删除', {type: 'warning'}).then(() => {
        this.$axios.post('/user/deleteUser', this.$qs.stringify({id: data.id})).then(res => {
          if (res.code === 200) {
            this.getData();
            this.$message({type: 'success', message: '删除成功!'});
          }
        })
      }).catch(() => {
      });
    },
    handleEnable(data) {
      this.$confirm('确认启用改账号?', '提示', {type: 'success'}).then(() => {
        this.$axios.post('/user/enableUser', this.$qs.stringify({id: data.id})).then(res => {
          if (res.code === 200) {
            this.getData();
            this.$message({type: 'success', message: '禁用成功'});
          }
        })
      }).catch(() => {
      });
    },
    handleDisable(data) {
      this.$confirm('确认禁用改账号?', '提示').then(() => {
        this.$axios.post('/user/disableUser', this.$qs.stringify({id: data.id})).then(res => {
          if (res.code === 200) {
            this.getData();
            this.$message({type: 'success', message: '禁用成功'});
          }
        })
      }).catch(() => {
      });
    },
    currentChange(data) {
      this.currentPage = data;
      this.getData();
    },
    closeDialog() {
      this.dialog = false;
      this.userForm = {id: '', username: '', roleList: [], phone: '', email: ''};
      this.dialogType = 0;
      this.$refs['userForm'].resetFields();
    },
    getRoles() {
      this.$axios.post('/role/findAll').then(res => {
        if (res.code === 200) {
          this.roles = res.data;
        }
      })
    },
    getData() {
      let formData = new FormData();
      formData.append("page", this.currentPage + '');
      formData.append("size", this.pageSize);
      formData.append("username", this.search);
      this.$axios.post('/user/findAll', formData).then(res => {
        if (res.code === 200) {
          for (let index in res.data.content) {
            let roleNames = '';
            res.data.content[index].roleList.forEach(item => {
              roleNames += item.roleName + '、';
            });
            res.data.content[index].roleNames = roleNames.substring(0, roleNames.length - 1);
          }
          this.tableData = res.data.content;
          this.total = res.data.totalElements;
        }
      })
    }
  }, created() {
    this.getData();
    this.getRoles();
  }
}
</script>
